﻿namespace HutongGames.PlayMaker
{
    using System;
    using UnityEngine;

    public class DelayedEvent
    {
        private FsmEventData eventData;
        private bool eventFired;
        private readonly FsmEventTarget eventTarget;
        private readonly Fsm fsm;
        private readonly HutongGames.PlayMaker.FsmEvent fsmEvent;
        private float timer;

        public DelayedEvent(Fsm fsm, HutongGames.PlayMaker.FsmEvent fsmEvent, float delay)
        {
            this.fsm = fsm;
            this.timer = delay;
            this.fsmEvent = fsmEvent;
            this.eventData = new FsmEventData(Fsm.EventData);
        }

        public DelayedEvent(Fsm fsm, string fsmEventName, float delay)
        {
            this.fsm = fsm;
            this.timer = delay;
            this.fsmEvent = HutongGames.PlayMaker.FsmEvent.GetFsmEvent(fsmEventName);
            this.eventData = new FsmEventData(Fsm.EventData);
        }

        public DelayedEvent(PlayMakerFSM fsm, HutongGames.PlayMaker.FsmEvent fsmEvent, float delay) : this(fsm.Fsm, fsmEvent, delay)
        {
        }

        public DelayedEvent(PlayMakerFSM fsm, string fsmEventName, float delay) : this(fsm.Fsm, fsmEventName, delay)
        {
        }

        public DelayedEvent(Fsm fsm, FsmEventTarget eventTarget, HutongGames.PlayMaker.FsmEvent fsmEvent, float delay) : this(fsm, fsmEvent, delay)
        {
            this.eventTarget = eventTarget;
        }

        public DelayedEvent(Fsm fsm, FsmEventTarget eventTarget, string fsmEvent, float delay) : this(fsm, fsmEvent, delay)
        {
            this.eventTarget = eventTarget;
        }

        public void Update()
        {
            this.timer -= Time.deltaTime;
            if (this.timer < 0f)
            {
                FsmEventData eventData = Fsm.EventData;
                Fsm.EventData = this.eventData;
                if (this.eventTarget == null)
                {
                    this.fsm.Event(this.fsmEvent);
                }
                else
                {
                    this.fsm.Event(this.eventTarget, this.fsmEvent);
                }
                this.eventFired = true;
                this.eventData = null;
                Fsm.EventData = eventData;
            }
        }

        public static bool WasSent(DelayedEvent delayedEvent)
        {
            return ((delayedEvent == null) || delayedEvent.eventFired);
        }

        public bool Finished
        {
            get
            {
                return this.eventFired;
            }
        }

        public HutongGames.PlayMaker.FsmEvent FsmEvent
        {
            get
            {
                return this.fsmEvent;
            }
        }

        public float Timer
        {
            get
            {
                return this.timer;
            }
        }
    }
}

